from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import re,redis,random,string,jwt,time
from django.http.response import HttpResponse
from captcha.image import ImageCaptcha
from django.contrib.auth.hashers import make_password,check_password
from shop.settings import SECRET_KEY
# Create your views here.
class ImgCode(APIView):
    def get(self,request,uuid):
        img_code = ''.join(random.sample(string.ascii_letters+string.digits,4))
        r = redis.Redis(host='127.0.0.1',port=6379,db=5)
        r.set(uuid,img_code,ex=180)
        r.close()
        cap = ImageCaptcha()
        img = cap.generate(img_code)
        return HttpResponse(content=img,content_type='image/png')

    #校验图片验证码
    def post(self,request,uuid):
        #接收参数
        code = request.data.get('code')
        #校验参数
        if not code:
            return Response({'message':'请输入验证码','code':400})
        #具体逻辑
        #判断用户传过来的验证码和数据库的验证码是否一致
        rds = redis.Redis(host='127.0.0.1',port=6379,db=5)
        sys_code = rds.get(uuid)
        rds.close()
        if not sys_code:
            return Response({'message':'验证码已经过期','code':401})
        if code.upper() != sys_code.decode().upper():
            return Response({'message':'验证码错误','code':402})

        #返回响应
        return Response({'message':'ok','code':200})

class LoginView(APIView):
    def post(self,request):
        data = request.data
        if not all([
            data['username'],
            data['password'],
            data['code'],
            data['uuid']
        ]):
            return Response({'message':'前端数据不完整','code':400})

        rds = redis.Redis(host='127.0.0.1', port=6379, db=5)
        sys_code = rds.get(data.get('uuid'))
        rds.close()
        if not sys_code:
            return Response({'message': '验证码已经过期', 'code': 401})
        if data.get('code').upper() != sys_code.decode().upper():
            return Response({'message': '验证码错误', 'code': 402})

        user = UserModel.objects.filter(username=data.get('username')).first()
        if not user:
            return Response({'message':'密码错误','code':403})
        #校验密码是否一致
        rs = check_password(data.get('password'),user.password)
        if not rs:
            return Response({'message':'错误','code':404})
        #jwt.decode()  #解码
        #jwt.encode()  #编码
        token = jwt.encode({
            'user_id':user.id,
            'username':user.username,
            'exp':int(time.time()) + 86400,  #设置token有效期
        },SECRET_KEY,algorithm='HS256')

        return Response({
            'message':'登陆成功',
            'code':20000,
            'data':{
            'token':token
        }})

class RegView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        if not all([username,password,mobile]):
            return Response({'message':'数据不完整','code':400})
        user = UserModel.objects.filter(username=username).first()
        if user:
            return Response({'message':'该用户已经注册','code':401})
        rule = r'^1[3-9]\d{9}$'
        if not re.findall(rule,mobile):  #匹配上之后返回列表，没有匹配上返回空列表
            return Response({'message':'手机号格式不对','code':402})
        password1 = make_password(password)
        UserModel.objects.create(username=username,password=password1,mobile=mobile)
        return Response({'message':'ok','code':200})

class UserInfoView(APIView):
    def get(self,requets):
        token = requets.query_params.get('token')
        print(token)
        try:
           payload = jwt.decode(token,SECRET_KEY,algorithms='HS256')
        except Exception as e:
            print(e)
            return Response({'message':'用户没有登录','code':403})
        user_id = payload.get('user_id')
        user_info = UserModel.objects.filter(id=user_id).first()
        if not user_info:
            return Response({'message':'用户没有登录','code':404})
        return Response({
            'code':20000,
            'message':'获取用户信息成功',
            'data':{
                'name':user_info.username,
                'avatar':'https://img0.baidu.com/it/u=2335072147,3242329848&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
            }
        })

class LoginOut(APIView):
    def post(self,request):
        return Response({
            'message':'退出成功',
            'code':20000
        })

